package com.siqi.hr.system.organization.service;

import com.siqi.hr.common.Constants;
import com.siqi.hr.common.utils.FileUtils;
import com.siqi.hr.common.utils.TableConstant;
import com.siqi.hr.system.common.dao.intf.CommonOperationDao;
import com.siqi.hr.system.common.model.Module;
import com.siqi.hr.system.common.model.ModuleType;
import com.siqi.hr.system.common.model.ReturnInfo;
import com.siqi.hr.system.common.sql.STable;
import com.siqi.hr.system.custom.entity.EntityRecord;
import com.siqi.hr.system.organization.dao.intf.DeptDao;
import com.siqi.hr.system.organization.dao.intf.EmployeeDao;
import com.siqi.hr.system.organization.entity.Dept;
import com.siqi.hr.system.organization.entity.Employee;
import com.siqi.hr.system.organization.entity.Role;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 员工信息维护service层
 * @author     xiaogq
 * @date       2016-07-21
 */
@Service("employeeService")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class EmployeeService {

    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private CommonOperationDao commonOperationDao;
    @Autowired
    private DeptDao deptDao;

    /**
     * 员工登录验证
     * @param request
     * @param session
     * @param employee（员工信息）
     * @return
     * @throws Exception
     */
    public ReturnInfo checkLogin(HttpServletRequest request, HttpSession session, Employee employee)throws Exception{
        String deptTableName = TableConstant.DEPT_TNAME;
        ReturnInfo info = new ReturnInfo();
        //根据用户名获得用户信息
        Employee emp = employeeDao.queryEmpAndDepAndRoleByLogUsername(employee.getJobNumber().toUpperCase());
        String emppwd = (emp == null) || (emp.getPassword() == null) ? "" : emp .getPassword();
        //验证登陆的用户名密码是否正确
        if ((emp == null) || (!employee.getPassword().trim().equals(emppwd.trim()))) {
            info.setError("用户名或密码错误！");
            return info;
        }
        //验证员工信息是否完善、部门，角色信息
        if ((emp.getRole() == null) || (emp.getDept() == null) || (emp.getRole().getId() == null) || (emp.getDept().getId() == null)) {
            info.setError("员工信息不完善，请设置角色和部门！");
        } else if (emp.isFlag()) {
            info.setError("员工被禁用！");
        } else {
            Dept dept = emp.getDept();
            if (dept.isFlag()) {
                info.setError("您的部门被禁用！");
            } else {
                Role role = emp.getRole();
                //登陆的模块
                int moduleid = 0;
                //如果当前登陆系统的人是管理员角色,则默认登陆系统设置模块
                if(role.getId().equals(Constants.ROOTROLEID)){
                    moduleid = 1;
                }else{//如果当前登陆系统的人不是管理员角色,则默认tms系统业务模块
                    moduleid = 2;
                }
                info.setSuccess(true);
                ModuleType moduleType = ModuleType.getModuleType(moduleid);
                info.setModule(new Module(moduleType.getCode(), moduleType.name(), moduleType.getModuleMark(), moduleType.getDesc(),false));
                info.setLoginName(emp.getJobNumber());
                session.setAttribute("emp", emp);
                session.setAttribute("role", role);
                session.setAttribute("dept", dept);
                session.setAttribute("isadmin",role.getIsAdmin());
                session.setAttribute("module", moduleid);
                session.setAttribute("isFront",  moduleid == 1 ? false : true);
                Dept rootdept = deptDao.queryRootDept(deptTableName);
                session.setAttribute("rootdept", rootdept);
                try {
                    //验证通过后修改该用户最近登录的时间
                    employeeDao.updateEmpLoginDate(emp.getId());
                } catch (RuntimeException localRuntimeException) {
                }
            }
        }
        return info;
    }

    /**
     * 删除用户数据
     * @param tableName（表名）
     * @param dataId（数据id）
     * @throws Exception
     */
    public JSONObject deleteEmployee(final String tableName, final String dataId) throws Exception{
        JSONObject obj = new JSONObject();
        STable table = new STable(tableName);
        obj.put("success","success");
        if(dataId.equals(Constants.ROOTEMPID)){
            obj.put("success","nodel");
        }else{
            commonOperationDao.deleteTData(table, dataId);
        }
        return obj;
    }

    /**
     * 添加员工信息
     * @param dataMap             前台页面form表单提交的值
     * @param entityRecord       实体对象
     * @param emp                 当前登陆系统用户信息对象
     * @param multipartRequest  文件上传对象
     * @return
     * @throws Exception
     */
    public int addSaveEmployee(Map<String,Object> dataMap, EntityRecord entityRecord, Employee emp, DefaultMultipartHttpServletRequest multipartRequest) throws Exception{
        int counts = 0;
        //处理文件上传
        if(multipartRequest != null){
            for (Map.Entry<String, MultipartFile> entry : multipartRequest.getFileMap().entrySet()) {
                MultipartFile file = entry.getValue();
                byte[] contents = file.getBytes();
                if (contents == null || contents.length == 0) {
                    continue;
                }
                String filePath = FileUtils.uploadFiles(file);
                dataMap.put(file.getName(),filePath);
            }
        }
        String deptIds = dataMap.get("pk_t_2_1") == null ? "" : dataMap.get("pk_t_2_1").toString();
        if(StringUtils.isNotBlank(deptIds) && deptIds.contains(",")){
            String [] deptArrs = deptIds.split(",");
            dataMap.put("pk_t_2_1",deptArrs[0]);
        }
        String id = commonOperationDao.addTData(dataMap, entityRecord, emp);
        if(StringUtils.isNotBlank(id)){
            counts = 1;
        }
        return counts;
    }

    /**
     * 修改员工信息
     * @param dataMap
     * @param entityRecord
     * @param emp
     * @param id
     * @param multipartRequest
     * @return
     * @throws Exception
     */
    public int updateEmployeeData(Map<String,Object> dataMap, EntityRecord entityRecord, Employee emp, String id, DefaultMultipartHttpServletRequest multipartRequest) throws Exception{
        //处理文件上传
        if(multipartRequest != null){
            for (Map.Entry<String, MultipartFile> entry : multipartRequest.getFileMap().entrySet()) {
                MultipartFile file = entry.getValue();
                byte[] contents = file.getBytes();
                if (contents == null || contents.length == 0) {
                    continue;
                }
                String filePath = FileUtils.uploadFiles(file);
                dataMap.put(file.getName(),filePath);
            }
        }
        String deptIds = dataMap.get("pk_t_2_1") == null ? "" : dataMap.get("pk_t_2_1").toString();
        if(StringUtils.isNotBlank(deptIds) && deptIds.contains(",")){
            String [] deptArrs = deptIds.split(",");
            dataMap.put("pk_t_2_1",deptArrs[0]);
        }
        return commonOperationDao.updateTData(dataMap, entityRecord, emp, id);
    }

    /**
     * 修改用户密码时验证原密码是否正确
     * @author           xiaogq
     * @param empid     员工id
     * @param pwd        原密码
     * @return
     */
    public Boolean loginPwdConfirm(String empid, String pwd) {
        return employeeDao.loginPwdConfirm(empid, pwd);
    }

    /**
     * 修改用户密码
     * @author           xiaogq
     * @param empid     员工id
     * @param pwd        新密码
     * @return
     */
    public void updatePwd(String empid, String pwd) {
        employeeDao.updatePwd(empid, pwd);
    }

    /**
     * 清空用户密码
     * @author                 xiaogq
     * @param employeeId     员工id
     * @return
     */
    public void emptyEmployeePassword(String employeeId) {
        employeeDao.emptyEmployeePassword(employeeId);
    }

    /**
     * 获取员工最大工号编号
     * @author                 xiaogq
     * @param tableName     （表名）
     * @return
     */
    public int getMaxJobNumber(String tableName) {
        return employeeDao.getMaxJobNumber(tableName);
    }

    /**
     * 停用用户数据
     * @param tableName（表名）
     * @param dataId（数据id）
     * @throws Exception
     */
    public int disableEmployee(final String tableName, final String dataId) throws Exception{
        STable table = new STable(tableName);
        return commonOperationDao.disableTDate(table, dataId);
    }

    /**
     * 启用用户数据
     * @param tableName（表名）
     * @param dataId（数据id）
     * @throws Exception
     */
    public void enableEmployee(final String tableName, final String dataId) throws Exception{
        STable table = new STable(tableName);
        commonOperationDao.enableTDate(table, dataId);
    }

    /**
     * 获取同一岗位员工
     * @author ChenL
     */
    public List<Map<String,Object>> getEmpListByPostId(String postId,String empTableName,String deptTableName,String zEmpPostTableName){
        return employeeDao.getEmpListByPostId(postId,empTableName,deptTableName,zEmpPostTableName);
    }

    /**
     * 根据岗位id模糊查询人员
     * @author ChenL
     */
    public List<Map<String, Object>> searchEmpByPostId(String empTableName,String deptTableName,String postId,String search){
        return employeeDao.searchEmpByPostId(empTableName,deptTableName,postId,search);
    }

    /**
     * 获取所有的员工id及姓名
     * @author xiaogq
     * @param tableName    员工表名
     * @return
     */
    public JSONArray getAllEmpName(String tableName){
        JSONArray arrays = new JSONArray();
        List<Map<String, Object>> empList = employeeDao.getAllEmpName(tableName);
        for(Map<String, Object> empMap : empList){
            JSONObject obj =  new JSONObject();
            obj.put("id",empMap.get("id") == null ? "" : empMap.get("id"));
            obj.put("name",empMap.get("name") == null ? "" : empMap.get("name"));
            arrays.add(obj);
        }
        return arrays;
    }

}
